import tkinter as tk
from tkinter import ttk, messagebox, Canvas
from PIL import Image, ImageTk
import os
from src.core.item_manager import delete_item
from src.storage.file_manager import save_to_file
from src.ui.tkinter.screens.edit_screen import init_edit_screen

LIGHT_PINK = "#FFD1DC"
LIGHT_BROWN = "#E7BD6E"
LIGHT_BROWN_ACTIVE = "#D4A76A"
DARK_BROWN = "#6B4832"

def init_selection_screen(parent, items):
    """
    Initializes and displays the selection screen with pet items.
    
    Creates the main selection interface with a list of pet items, allowing
    users to view, edit, or delete items. Includes navigation buttons for
    returning to the launch screen or creating new items.
    
    Args:
        parent (tk.Widget): The parent container for the selection screen
        items (list): List of pet items to display in the selection screen
    """
    style = ttk.Style()
    style.configure(
        "Brown.TButton",
        font=("SimHei", 10, "bold"),
        foreground=DARK_BROWN,
        background=LIGHT_BROWN,
        padding=8,
        borderwidth=1,
        bordercolor=LIGHT_BROWN_ACTIVE,
        relief="solid"
    )
    style.map(
        "Brown.TButton",
        background=[("active", LIGHT_BROWN_ACTIVE)],
        foreground=[("active", DARK_BROWN)]
    )
    
    main_frame = tk.Frame(parent, bg=LIGHT_PINK)
    main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
    header = tk.Frame(main_frame, bg=LIGHT_BROWN)
    header.pack(fill=tk.X, pady=10)
    tk.Label(header, text="Electronic Pet Collection ", font=("SimHei", 18, "bold"), bg=LIGHT_BROWN).pack(side=tk.LEFT)
    btn_frame = tk.Frame(header, bg=LIGHT_BROWN)
    btn_frame.pack(side=tk.RIGHT)

    ttk.Button(btn_frame, text="Add pets", command=lambda: go_to_create(parent), style="Brown.TButton", width=10).pack(side=tk.LEFT, padx=3)
    ttk.Button(btn_frame, text="Save", command=lambda: save_items(items), style="Brown.TButton", width=10).pack(side=tk.LEFT, padx=3)
    ttk.Button(btn_frame, text="Load", command=lambda: load_items(parent), style="Brown.TButton", width=10).pack(side=tk.LEFT, padx=3)
    ttk.Button(btn_frame, text="Return", command=lambda: go_to_launch(parent), style="Brown.TButton", width=10).pack(side=tk.LEFT, padx=3)

    display_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    display_frame.pack(fill=tk.BOTH, expand=True, pady=10)
    tk.Label(display_frame, text="All pets", font=("SimHei", 12), bg=LIGHT_PINK).pack(anchor=tk.W)

    scroll = tk.Scrollbar(display_frame)
    scroll.pack(side=tk.RIGHT, fill=tk.Y)
    canvas = Canvas(display_frame, yscrollcommand=scroll.set)
    canvas.pack(fill=tk.BOTH, expand=True)
    scroll.config(command=canvas.yview)
    global inner_frame
    inner_frame = tk.Frame(canvas, bg=LIGHT_PINK)
    canvas.create_window((0, 0), window=inner_frame, anchor="nw")

    refresh_display(parent, inner_frame, items)

    inner_frame.update_idletasks()
    canvas.config(scrollregion=canvas.bbox("all"))

    delete_frame = tk.Frame(main_frame, bg=LIGHT_PINK)
    delete_frame.pack(fill=tk.X, pady=20)
    tk.Label(delete_frame, text="input ID to delete:", font=("SimHei", 12), bg=LIGHT_PINK).pack(side=tk.LEFT, padx=10)
    global delete_id_entry
    delete_id_entry = tk.Entry(delete_frame, width=10, font=("SimHei", 12))
    delete_id_entry.pack(side=tk.LEFT, padx=10)
    ttk.Button(delete_frame, text="delete", command=lambda: delete_selected(items), style="Brown.TButton").pack(side=tk.LEFT, padx=10)
    
    global search_entry
    search_entry = tk.Entry(delete_frame, width=12, font=('SimHei', 10))
    search_entry.pack(side=tk.LEFT, padx=3)
    ttk.Button(delete_frame, text="Search", command=lambda: search_items(parent, items), style="Brown.TButton", width=6).pack(side=tk.LEFT, padx=2)
    ttk.Button(delete_frame, text="Sort", command=lambda: sort_items(parent, items), style="Brown.TButton", width=6).pack(side=tk.LEFT, padx=2)
    ttk.Button(delete_frame, text="Stats", command=lambda: show_stats(items), style="Brown.TButton", width=6).pack(side=tk.LEFT, padx=2)

def refresh_display(parent, inner_frame, items):
    """
    Refreshes the display of pet items in the selection screen.
    
    Clears the current display and updates it with the provided list of pet items.
    If the list is empty, displays a message indicating no pets are available.
    
    Args:
        parent (tk.Widget): The parent container for the selection screen
        inner_frame (tk.Frame): The frame where pet items are displayed
        items (list): List of pet items to display in the selection screen
    """
    for widget in inner_frame.winfo_children():
        widget.destroy()

    if not items:
        tk.Label(inner_frame, text="NO pets\n", font=("SimHei", 10), bg=LIGHT_PINK).grid(row=0, column=0, columnspan=2, pady=5)
    else:
        tk.Label(inner_frame, text=f"Have {len(items)}pets(up date to 4)\n", font=("SimHei", 10), bg=LIGHT_PINK).grid(row=0, column=0, columnspan=2, pady=5)
        for i, pet in enumerate(items, 1):
            pet_info = (
                f"pet {i}:\n"
                f"  ID: {pet['id']}\n"
                f"  name: {pet['name']}\n"
                f"  item_type: {pet['item_type']}\n" 
                f"  age: {pet['age']}\n"
                "-------------------------\n"
            )
            tk.Label(inner_frame, text=pet_info, font=("SimHei", 10), bg=LIGHT_PINK, justify=tk.LEFT).grid(row=i, column=0, padx=5, pady=5, sticky="w")

            try:
                img_path = pet.get('image_path')
                if img_path and os.path.exists(img_path):
                    img = Image.open(img_path)
                    img = img.resize((100, 100), Image.Resampling.LANCZOS)  
                    photo = ImageTk.PhotoImage(image=img)
                    img_label = tk.Label(inner_frame, image=photo, bg=LIGHT_PINK)
                    img_label.grid(row=i, column=1, padx=5, pady=5)
                    img_label.image = photo
                else:
                    tk.Label(inner_frame, width=100, height=100, bg=LIGHT_PINK).grid(row=i, column=1, padx=5, pady=5)
                
                edit_btn = tk.Button(inner_frame, text="Edit", 
                                    command=lambda pet_id=pet['id']: go_to_edit(parent, items, pet_id),
                                    bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                                    relief="solid", borderwidth=1)
                edit_btn.grid(row=i, column=2, padx=5, pady=5)
            except Exception as e:
                tk.Label(inner_frame, width=100, height=100, bg=LIGHT_PINK).grid(row=i, column=1, padx=5, pady=5)

def delete_selected(items):
    """
    Deletes the pet item with the specified ID from the list of items.
    
    Prompts the user for the pet ID to delete, validates the input, and removes
    the pet from the list if found. Updates the display after deletion.
    
    Args:
        items (list): List of pet items from which to delete an item
    """
    try:
        pet_id = int(delete_id_entry.get().strip())
        success, msg = delete_item(items, pet_id)
        if success:
            parent = inner_frame.master.master.master.master
            refresh_display(parent, inner_frame, items)
            messagebox.showinfo("success", msg)
            delete_id_entry.delete(0, tk.END)
        else:
            messagebox.showerror("Error", msg)
    except ValueError:
        messagebox.showerror("Error", "Please input right number ID")

def save_items(items):
    """
    Saves the current list of pet items to a JSON file.
    
    Prompts the user for confirmation before saving, and updates the display
    after successful saving.
    
    Args:
        items (list): List of pet items to save to the JSON file
    """
    try:
        save_to_file(items, "data/pets.json")
        messagebox.showinfo("success", "save to data/pets.json")
    except Exception as e:
        messagebox.showerror("Error", f"save false: {str(e)}")

def load_items(parent):
    """
    Loads pet items from a JSON file and updates the display.
    
    Prompts the user for confirmation before loading, and updates the display
    with the loaded pet items. If the file is not found, displays an error message.
    
    Args:
        parent (tk.Widget): The parent container widget
    """
    try:
        from src.storage.file_manager import load_from_file
        loaded_items = load_from_file("data/pets.json", force_reload=True)  
        from src.ui.tkinter.main_window import update_items
        update_items(loaded_items)
        from src.ui.tkinter.main_window import show_screen
        show_screen("selection")
        global inner_frame
        refresh_display(parent, inner_frame, loaded_items)
        messagebox.showinfo("success", f"loaded {len(loaded_items)} pets")
    except FileNotFoundError:
        messagebox.showerror("error", "do not find data/pets.json")
    except Exception as e:
        messagebox.showerror("Error", f"Failed to load: {str(e)}")

def go_to_create(parent):
    """Jump to the creation interface"""
    from src.ui.tkinter.main_window import show_screen
    show_screen("creation")

def go_to_edit(parent, items, pet_id):
    """Jump to the editing interface"""
    init_edit_screen(parent, items, pet_id)

def go_to_launch(parent):
    """Jump to the launch interface"""
    from src.ui.tkinter.main_window import show_screen
    show_screen("launch")

def search_items(parent, items):
    """Search for pets function"""
    search_term = search_entry.get().lower().strip()
    if not search_term:
        refresh_display(parent, inner_frame, items)
        return None
    
    filtered_items = []
    for item in items:
        if (search_term in str(item['id']).lower() or 
            search_term in item['name'].lower() or 
            search_term in item['item_type'].lower()):
            filtered_items.append(item)
    
    refresh_display(parent, inner_frame, filtered_items)
    if not filtered_items:
        messagebox.showinfo("Search Result", f"Not found pets contain '{search_term}'")

def sort_items(parent, items):
    """Sort pets function"""
    sort_window = tk.Toplevel(parent)
    sort_window.title("Sort Options")
    sort_window.geometry("300x200")
    sort_window.configure(bg=LIGHT_PINK)
    
    tk.Label(sort_window, text="Select sorting method:", font=("SimHei", 12), bg=LIGHT_PINK, fg="black").pack(pady=10)
    
    sort_var = tk.StringVar(value="id")
    
    tk.Radiobutton(sort_window, text="Sort by ID", variable=sort_var, value="id", 
                  bg=LIGHT_PINK, font=("SimHei", 10), fg="black").pack(pady=5, anchor=tk.W, padx=20)
    tk.Radiobutton(sort_window, text="Sort by Name", variable=sort_var, value="name", 
                  bg=LIGHT_PINK, font=("SimHei", 10), fg="black").pack(pady=5, anchor=tk.W, padx=20)
    tk.Radiobutton(sort_window, text="Sort by Age", variable=sort_var, value="age", 
                  bg=LIGHT_PINK, font=("SimHei", 10), fg="black").pack(pady=5, anchor=tk.W, padx=20)

    
    def apply_sort():
        """
        Applies sorting to pet items based on the selected criteria and updates display.
    
        Retrieves the chosen sort category (ID, Name, or Age), sorts the items 
        (case-insensitive for names, ascending order by default), refreshes the 
        item display with sorted results, and closes the sort selection window.
        """
        sort_by = sort_var.get()
        reverse = False
        
        if sort_by == "id":
            sorted_items = sorted(items, key=lambda x: x['id'], reverse=reverse)
        elif sort_by == "name":
            sorted_items = sorted(items, key=lambda x: x['name'].lower(), reverse=reverse)
        elif sort_by == "age":
            sorted_items = sorted(items, key=lambda x: x['age'], reverse=reverse)

        refresh_display(parent, inner_frame, sorted_items)
        sort_window.destroy()

    tk.Button(sort_window, text="Finish", command=apply_sort, 
              bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
              relief="solid", borderwidth=1, width=10).pack(pady=20)

def show_stats(items):
    """Show pet statistics"""
    if not items:
        messagebox.showinfo("Statistics", "No pet data available")
        return None
    
    total_pets = len(items)
    types_count = {}
    total_age = 0
    
    for item in items:
        pet_type = item['item_type']
        if pet_type in types_count:
            types_count[pet_type] += 1
        else:
            types_count[pet_type] = 1
        
        total_age += item['age']
    
    avg_age = total_age / total_pets if total_pets > 0 else 0

    stats_text = f"Total Pets: {total_pets}\n"
    stats_text += f"Average Age: {avg_age:.1f}\n\n"
    stats_text += "Pet Type Distribution:\n"
    
    for pet_type, count in types_count.items():
        percentage = (count / total_pets) * 100
        stats_text += f"- {pet_type}: {count} ({percentage:.1f}%)\n"
    
    messagebox.showinfo("Statistics", stats_text)
